package com.emns.web.yuedu;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.ckfinder.connector.utils.FileUtils;
import com.emns.pojo.Lanmu;
import com.emns.pojo.Yuedu;
import com.emns.service.yuedu.YueduService;
import common.ConfigUtils;
import common.DateUtils;
import common.PageInfo;

@Controller
@RequestMapping(value = "/yuedu")
public class YueduController implements ServletContextAware {

	@Autowired
	YueduService ys;
	private ServletContext servletContext;
	private String basePath;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	// 查找所有悦读数据
	@RequestMapping(value = "/queryPage")
	public String queryPage(Model model,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) String keyWord,
			@RequestParam(required = false) String startDate,
			@RequestParam(required = false) String endDate) {
		System.out.println("qiaoyahao:" + keyWord);
		PageInfo<Yuedu> pageInfo = new PageInfo<Yuedu>();
		if (pageNo == null) {
			pageNo = 1;
		}
		pageInfo.setPageNum(pageNo);
		ys.queryPageAll(keyWord, startDate, endDate, pageInfo);
		model.addAttribute("info", pageInfo);
		model.addAttribute("keyWord", keyWord);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		return "/yuedu_manager";
	}

	// 添加悦读数据
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Model model, Yuedu yuedu, int flanmu, int[] lanmu)
			throws Exception {
		yuedu.settUserUserId(1);
		yuedu.setPublishdate(new Date());
		yuedu.setReadingcount(0);
		ys.add(yuedu, flanmu, lanmu);
		return "redirect:/yuedu_add";
	}

	// 更新悦读数据
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Model model, Yuedu yuedu, int flanmu, int[] lanmu) {
		yuedu.settUserUserId(1);
		yuedu.setPublishdate(new Date());
		ys.update(yuedu, flanmu, lanmu);
		return "redirect:/yuedu/queryPage";
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(String type, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		commonsMultipartResolver.setDefaultEncoding("utf-8");
		String url = "";
		// if ("video".equals(type)) {
		// basePath = "/home/qyh/workdir/emns/uploadFile";
		// } else if ("pic".equals(type)) {
		basePath = servletContext.getRealPath("/")
				+ ConfigUtils.getAppConfig("yuedu.picpath");
		// }
		System.out.println(basePath);
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multipartRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multipartRequest.getFile((String) iter
						.next());
				if (file != null) {
					String suffix = FileUtils.getFileExtension(file
							.getOriginalFilename());
					String fileName = DateUtils.getFormatDate(new Date(),
							"yyyyMMddHHmmssSSS") + "." + suffix;
					url = saveFileFromInputStream(file.getInputStream(),
							basePath, fileName.toLowerCase());
				}
			}
		}
		response.setStatus(200);
		response.getWriter().append(url);
	}

	// 删除悦读数据
	@RequestMapping(value = "/delete")
	public String delete(Model model, Integer[] yueduId,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) String keyWord,
			@RequestParam(required = false) String startDate,
			@RequestParam(required = false) String endDate) {
		if (yueduId != null) {
			ys.delete(yueduId);
		} else {
			System.out.println("yueduId is null");
		}
		return "forward:/yuedu/queryPage";
	}

	private String saveFileFromInputStream(InputStream stream, String path,
			String filename) throws IOException {
		String url = path + "/" + filename;
		FileOutputStream fs = new FileOutputStream(url);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
		return filename;
	}

	@RequestMapping(value = "/edit_view")
	public String view(Model model, HttpServletRequest request, Integer id) {
		List<Lanmu> lanmu = (List<Lanmu>) request.getSession()
				.getServletContext().getAttribute("secondLanmu");
		List<Lanmu> flanmu = (List<Lanmu>) request.getSession()
				.getServletContext().getAttribute("firstLanmu");
		List<Lanmu> list = new ArrayList<Lanmu>();
		Lanmu firstLanmu = new Lanmu();
		Map<Integer, Boolean> map = ys.getLanmuZiyuanById(id);
		for (Lanmu tmp : lanmu) {
			Lanmu lm = new Lanmu();
			lm.setId(tmp.getId());
			lm.setName(tmp.getName());
			if (map.containsKey(tmp.getId()))
				lm.setSeleted(true);
			else
				lm.setSeleted(false);
			firstLanmu.setId(tmp.gettLanmuId());
			list.add(lm);
		}
		for (Lanmu tmp : flanmu) {
			if (tmp.getId() == firstLanmu.getId()) {
				firstLanmu = tmp;
				break;
			}
		}
		Yuedu yuedu = ys.getYueduById(id);
		model.addAttribute("model", yuedu);
		model.addAttribute("fLanmu", firstLanmu);
		model.addAttribute("sLanmu", list);

		return "/yuedu_modify";

	}
}
